<?php



namespace App\Http\Controllers\Backend;
use App\Http\Requests\Company\RoleRequest;
use App\Services\Member\Models\Role;
use App\Services\Member\Models\User;
use App\Services\Company\Models\CompanyRole;
use App\Services\Company\Interfaces\CompanyRoleServiceInterface;
use App\Services\Company\Services\CompanyRoleService;

class CompanyRoleController extends BaseController
{

    /**
     * @var CompanyRoleService
     */
    protected $companyRoleService;


    public function __construct(
        CompanyRoleServiceInterface $companyRoleService

    ) {
        $this->companyRoleService = $companyRoleService;

    }


    public function index()
    {

        $roles =   CompanyRole::query()->with(['privileges','expireds'])->get()->toArray();

        return $this->successData(compact('roles'));
    }




    public function detail($id)
    {
        $role = $this->companyRoleService->get($id);
        return $this->successData(compact('role'));
    }

    public function store(RoleRequest $request,Role $role)
    {
        $data = $request->filldata();
        $role->fill($data)->save();
        $role->privileges()->attach($data['privilege_ids']);
        return $this->success(__('插入会员记录成功'));
    }

    public function edit($id)
    {
        $role = $this->companyRoleService->get($id);

        return $this->successData(compact('role'));
    }

    public function update(RoleRequest $request, $id)
    {
        $data =  $request->filldata();
        $role = Role::findOrFail($id);
        $role->fill($data)->save();
        $role->privileges()->sync($data['privilege_ids']);

        return $this->success();
    }

    public function delete($id)
    {
        if (User::query()->where('role_id', $id)->exists()) {
            return $this->error(__('当前VIP下存在用户无法删除'));
        }

        Role::destroy($id);

        return $this->success(__('删除会员成功'));
    }



}
